package org.smartopen.unionpay.openapi.config;

import org.smartopen.unionpay.openapi.constant.MqConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
@ConditionalOnClass(Queue.class)
public class UnionPayRabbitConfig {

    /*********************    默认交换机    *****************/
    @Bean
    DirectExchange defaultExchange() {
        return new DirectExchange(MqConstants.UNIONPAY_EXCHANGE, true, false);
    }

    /*********************   任务消息队列    *****************/
    @Bean
    public Queue UNIONPAY_QUEUE_PAY_NOTIFY_QUEUE_NAME() {
        return new Queue(MqConstants.UNIONPAY_PAY_NOTIFY_QUEUE_NAME, true, false, false);
    }

    @Bean
    public Queue UNIONPAY_QUEUE_REFUND_NOTIFY_QUEUE_NAME() {
        return new Queue(MqConstants.UNIONPAY_REFUND_NOTIFY_QUEUE_NAME, true, false, false);
    }
    @Bean
    Binding UNIONPAY_QUEUE_PAY_NOTIFY_QUEUE_NAME_Binding() {
        return BindingBuilder.bind(UNIONPAY_QUEUE_PAY_NOTIFY_QUEUE_NAME()).to(defaultExchange()).with(MqConstants.UNIONPAY_PAY_NOTIFY_QUEUE_NAME);
    }
    @Bean
    Binding UNIONPAY_QUEUE_REFUND_NOTIFY_QUEUE_NAME_Binding() {
        return BindingBuilder.bind(UNIONPAY_QUEUE_PAY_NOTIFY_QUEUE_NAME()).to(defaultExchange()).with(MqConstants.UNIONPAY_REFUND_NOTIFY_QUEUE_NAME);
    }

    /*********************    下面是延迟队列的配置    *****************/
    //转发队列
    @Bean
    public Queue repeatTradeQueue() {
        return new Queue(MqConstants.UNIONPAY_REPEAT_TRADE_QUEUE_NAME, true);
    }

    //绑定转发队列
    @Bean
    Binding repeatTradeBinding() {
        return BindingBuilder.bind(repeatTradeQueue()).to(defaultExchange()).with(MqConstants.UNIONPAY_REPEAT_TRADE_QUEUE_NAME);
    }

    //死信队列  -- 消息在死信队列上堆积，消息超时时，会把消息转发到转发队列，转发队列根据消息内容再把转发到指定的队列上
    @Bean
    public Queue deadLetterQueue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", MqConstants.UNIONPAY_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", MqConstants.UNIONPAY_REPEAT_TRADE_QUEUE_NAME);
        Queue queue = new Queue(MqConstants.UNIONPAY_DEAD_LETTER_QUEUE_NAME, true, false, false, arguments);
        return queue;
    }

    //绑定死信队列
    @Bean
    public Binding deadLetterBinding() {
        return BindingBuilder.bind(deadLetterQueue()).to(defaultExchange()).with(MqConstants.UNIONPAY_DEAD_LETTER_QUEUE_NAME);
    }

}


